"""
产品管理API
"""
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from app.models.product import Product
from app.extensions import db


products_bp = Blueprint('products', __name__, url_prefix='/api')


@products_bp.route('/products', methods=['GET'])
@jwt_required()
def get_products():
    """获取产品列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        search = request.args.get('search', '')
        workshop = request.args.get('workshop', '')
        
        # 构建查询
        query = Product.query
        
        # 搜索条件
        if search:
            query = query.filter(
                db.or_(
                    Product.product_name.like(f'%{search}%'),
                    Product.nominal_grade.like(f'%{search}%'),
                    Product.merged_grade.like(f'%{search}%'),
                    Product.merge_file.like(f'%{search}%')
                )
            )
        
        # 车间过滤
        if workshop:
            query = query.filter(Product.workshop == workshop)
        
        # 分页查询
        pagination = query.order_by(Product.id.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        products = [product.to_dict() for product in pagination.items]
        
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': {
                'products': products,
                'pagination': {
                    'page': page,
                    'per_page': per_page,
                    'total': pagination.total,
                    'pages': pagination.pages
                }
            }
        })
        
    except Exception as e:
        print(f"获取产品列表失败: {str(e)}")
        return jsonify({
            'code': 500,
            'message': f'获取产品列表失败: {str(e)}'
        }), 500


@products_bp.route('/products', methods=['POST'])
@jwt_required()
def create_product():
    """创建产品"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['workshop', 'product_name', 'nominal_grade', 'merged_grade', 'merge_file']
        for field in required_fields:
            if not data.get(field):
                return jsonify({
                    'code': 400,
                    'message': f'{field} 不能为空'
                }), 400
        
        # 创建产品
        product = Product(
            workshop=data['workshop'],
            product_name=data['product_name'],
            nominal_grade=data['nominal_grade'],
            merged_grade=data['merged_grade'],
            merge_file=data['merge_file'],
            is_active=data.get('is_active', True)
        )
        
        db.session.add(product)
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '创建成功',
            'data': product.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        print(f"创建产品失败: {str(e)}")
        return jsonify({
            'code': 500,
            'message': f'创建产品失败: {str(e)}'
        }), 500


@products_bp.route('/products/<int:product_id>', methods=['PUT'])
@jwt_required()
def update_product(product_id):
    """更新产品"""
    try:
        product = Product.query.get_or_404(product_id)
        data = request.get_json()
        
        # 更新字段
        product.workshop = data.get('workshop', product.workshop)
        product.product_name = data.get('product_name', product.product_name)
        product.nominal_grade = data.get('nominal_grade', product.nominal_grade)
        product.merged_grade = data.get('merged_grade', product.merged_grade)
        product.merge_file = data.get('merge_file', product.merge_file)
        product.is_active = data.get('is_active', product.is_active)
        
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '更新成功',
            'data': product.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        print(f"更新产品失败: {str(e)}")
        return jsonify({
            'code': 500,
            'message': f'更新产品失败: {str(e)}'
        }), 500


@products_bp.route('/products/<int:product_id>', methods=['DELETE'])
@jwt_required()
def delete_product(product_id):
    """删除产品"""
    try:
        product = Product.query.get_or_404(product_id)
        
        db.session.delete(product)
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '删除成功'
        })
        
    except Exception as e:
        db.session.rollback()
        print(f"删除产品失败: {str(e)}")
        return jsonify({
            'code': 500,
            'message': f'删除产品失败: {str(e)}'
        }), 500


@products_bp.route('/products/batch', methods=['DELETE'])
@jwt_required()
def batch_delete_products():
    """批量删除产品"""
    try:
        data = request.get_json()
        product_ids = data.get('ids', [])
        
        if not product_ids:
            return jsonify({
                'code': 400,
                'message': '请选择要删除的产品'
            }), 400
        
        # 批量删除
        Product.query.filter(Product.id.in_(product_ids)).delete(synchronize_session=False)
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': f'成功删除 {len(product_ids)} 个产品'
        })
        
    except Exception as e:
        db.session.rollback()
        print(f"批量删除产品失败: {str(e)}")
        return jsonify({
            'code': 500,
            'message': f'批量删除产品失败: {str(e)}'
        }), 500


@products_bp.route('/products/workshops', methods=['GET'])
@jwt_required()
def get_workshops():
    """获取车间列表"""
    try:
        workshops = db.session.query(Product.workshop).distinct().all()
        workshop_list = [workshop[0] for workshop in workshops]
        
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': workshop_list
        })
        
    except Exception as e:
        print(f"获取车间列表失败: {str(e)}")
        return jsonify({
            'code': 500,
            'message': f'获取车间列表失败: {str(e)}'
        }), 500